import React from 'react';
import ReactDom from 'react-dom';

class Counter extends React.Component {
   static defaultProps = {name: 'gugu'}
   constructor(props){
     super(props);
     this.state = {number: 0};
     console.log('1. Counter constructor 构造函数')
   }
   UNSAFE_componentWillMount(){
     console.log('2. counter componentWillMount 组件将要挂载')
   }
   add = ()=>{
     this.setState({
       number: this.state.number + 1
     })
   }
   shouldComponentUpdate(nextProps, nextState){
     console.log('5. counter shouldComponent 询问用户组件是否要更新，是否要重新渲染 ')
    return nextState.number%2===0; 
   }
   UNSAFE_componentWillUpdate(){
     console.log('6.counter componentWillUpdate 组件将要更新')
   }
   render(){
     console.log('3.counter render 组件渲染')
     return (
       <div>
         <p>{this.state.number}</p>
         <button onClick={this.add}>+</button>
         <hr/>
         {
           this.state.number >100 ? null :  <SubCounter count={this.state.number}/>
         }
       </div>
     )
   }
   componentDidUpdate(){
    console.log('7.counter componentDidUpdate 组件更新完成 ')
  }
   componentDidMount(){
    console.log('4.counter componentDidMount 组件挂载完成')
  }
}

class SubCounter extends React.Component {
  constructor(props){
    super(props);
    this.state={count: 0}
  }
  componentWillReceiveProps(){
    //当父组件将要传递给子组件新的属性的时候，子组件会触发此钩子
    console.log('3.subcounter componentwillreceiveprops')
  }
  componentWillUnmount(){
    console.log('1.subCounter 组件销毁')
  }
  //是静态方法
  static getDerivedStateFromProps(nextProps,prevState){
     let {count} = nextProps;
     return {count: count * 2}
  }
  render(){
    console.log('2.subcounter render')
    return (
      <h1>
       {this.state.count}
      </h1>
    )
  }
}


ReactDom.render(
  <Counter/>,
  document.getElementById('root')
)
